# -*- coding:utf-8 -*-
from fastapi import Request, HTTPException
from sqlalchemy.exc import OperationalError
from sqlalchemy import select
from core.curd import CRUDBase, IBaseDao
from app.entity.system import SysMenu


class SysMenuDao(IBaseDao):
    """
    测试模块服务层
    """

    def __init__(self, req: Request):
        self.db_session = req.app.state.db_async_session
        self.base = CRUDBase(SysMenu)

    async def get_menu_tree(self):
        async with self.db_session() as db:
            try:
                menus = []
                all_menus = await db.execute(select(SysMenu).filter(SysMenu.type == 0).order_by(SysMenu.sort))
                for menu in all_menus.scalars():
                    menus.append({
                        "id": menu.id,
                        "name": menu.name,
                        "authority": menu.authority,
                        "icon": menu.icon,
                        "openStyle": menu.open_style,
                        "pid": menu.pid,
                        "sort": menu.sort,
                        "url": menu.url,
                        "type": menu.type,
                        "children": []
                    })
                return menus
            except OperationalError as e:
                raise HTTPException(status_code=500, detail=str(e))
            except Exception as e:
                raise HTTPException(status_code=500, detail=str(e))
            finally:
                await db.close()

    @classmethod
    async def instance(cls, req: Request):
        return cls(req)
